<script setup>
import { useRoute, useRouter } from 'vue-router'
import { ref, inject, computed, watch } from 'vue'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { setDocumentText } from '@/utils/utils'
import documentApi from '@/apis/document'
import ArticleProse from '@/components/common/ArticleProse.vue'

const route = useRoute()
const router = useRouter()

const detail = ref({})
const list = inject('list')
const drawerRef = inject('drawerRef')
const isSmallPage = inject('isSmallPage')

const getDetail = async (id) => {
  detail.value = (await documentApi.detail(id)).data
  setDocumentText(detail.value.title)
}

const prevArticle = computed(() => {
  const index = list.value.findIndex((item) => item.id === detail.value.id)
  return list.value[index - 1] ?? null
})

const nextArticle = computed(() => {
  const index = list.value.findIndex((item) => item.id === detail.value.id)
  return list.value[index + 1] ?? null
})

const jumpDetail = (id) => {
  router.push({ name: 'documentHelpRead', params: { id } })
}

watch(
  () => route.params.id,
  async (val) => {
    if (val) {
      if (isSmallPage.value) drawerRef.value?.close()
      await getDetail(val)
    }
  },
  { immediate: true }
)
</script>

<template>
  <div class="p-4 text-[--el-text-color-primary]">
    <h1 class="text-xl font-bold mb-4">{{ detail.title }}</h1>
    <div class="mb-6 text-sm text-[--el-text-color-secondary]">{{ detail.update_at }}</div>
    <ArticleProse class="mb-8" :content="detail.content" />
    <div class="flex justify-between py-4 border-t border-[--el-border-color-light]">
      <div>
        <el-button
          v-if="prevArticle"
          :title="prevArticle.title"
          @click="jumpDetail(prevArticle.id)"
          link
        >
          <FontAwesomeIcon icon="arrow-left" class="mr-1" />
          <span>上一篇</span>
        </el-button>
      </div>
      <div class="text-right">
        <el-button
          v-if="nextArticle"
          :title="nextArticle.title"
          @click="jumpDetail(nextArticle.id)"
          link
        >
          <span>下一篇</span>
          <FontAwesomeIcon icon="arrow-right" class="ml-1" />
        </el-button>
      </div>
    </div>
  </div>
</template>
